create procedure [dbo].[SPMessagesGetById]
	@TopicId int
	,@MessageId int
AS
	set nocount on;

	select
		[TopicId]
      ,[MessageId]
      ,[MessageBody]
      ,[MessageCreationDate]
      ,[MessageLastEditDate]
      ,[ParentId]
      ,[UserId]
      ,[Active]
      ,[UserName]
      ,[UserSignature]
      ,[UserGroupId]
      ,[UserGroupName]
      ,[UserPhoto]
      ,[UserRegistrationDate]
	from 
		[dbo].[MessagesComplete]
	where
		TopicId = @TopicId
		and MessageId = @MessageId
GO

create procedure [dbo].[SPMessagesIsReplied]
	@TopicId int
	,@MessageId int
as
	set nocount on;
	
	select COUNT(*) 
	from dbo.Messages
	where
		TopicId = @TopicId
		and ParentId = @MessageId
go

alter table dbo.Messages add constraint FK_LastEditUser_Users
foreign key (MessageLastEditUser)
references dbo.Users ([UserId])
go

create procedure [dbo].[SPMessagesUpdate]
	@TopicId int
	,@MessageBody nvarchar(max)
	,@LastEditorUserId int
	,@MessageId int
as

	update dbo.Messages
	set
		MessageBody = @MessageBody,
		MessageLastEditUser = @LastEditorUserId,
		MessageLastEditDate = GETUTCDATE()
	where
		MessageId = @MessageId
	and
		TopicId = @TopicId
go